#!/usr/bin/env python3
"""
Analysis script for GPU correctness validation results
"""

import numpy as np
import struct

def read_binary_file(filename, dtype=np.float32):
    """Read binary files created by the validation framework"""
    try:
        with open(filename, 'rb') as f:
            data = f.read()
            # Convert bytes to float32 array
            num_elements = len(data) // 4
            floats = struct.unpack(f'{num_elements}f', data)
            return np.array(floats, dtype=np.float32)
    except Exception as e:
        print(f"Error reading {filename}: {e}")
        return None

def main():
    print("=== GPU Correctness Validation Analysis ===")
    print()
    
    # Read the binary files
    sequential = read_binary_file('output/sequential_result.npy')
    masquerading = read_binary_file('output/masquerading_result.npy')  
    reference = read_binary_file('output/reference_result.npy')
    
    if sequential is None or masquerading is None or reference is None:
        print("❌ Failed to read validation files")
        return
    
    print(f"Data shapes: {sequential.shape}, {masquerading.shape}, {reference.shape}")
    print(f"Total elements: {len(sequential)}")
    
    # Calculate errors
    seq_error = np.max(np.abs(sequential - reference))
    masq_error = np.max(np.abs(masquerading - reference))
    
    print(f"\n=== Validation Results ===")
    print(f"Sequential max error: {seq_error:.2e}")
    print(f"Masquerading max error: {masq_error:.2e}")
    
    # Check if results are correct
    tolerance = 1e-6
    seq_correct = seq_error < tolerance
    masq_correct = masq_error < tolerance
    
    if seq_correct and masq_correct:
        print("✅ VALIDATION PASSED: All results are correct")
        print("✅ Both sequential and masquerading modes produce identical results")
    else:
        print("❌ VALIDATION FAILED: Results differ significantly")
    
    # Show sample data
    print(f"\n=== Sample Data (first 10 elements) ===")
    print(f"Sequential:   {sequential[:10]}")
    print(f"Masquerading: {masquerading[:10]}")
    print(f"Reference:    {reference[:10]}")
    
    # Calculate statistics
    print(f"\n=== Statistics ===")
    print(f"Sequential - Mean: {np.mean(sequential):.6f}, Std: {np.std(sequential):.6f}")
    print(f"Masquerading - Mean: {np.mean(masquerading):.6f}, Std: {np.std(masquerading):.6f}")
    print(f"Reference - Mean: {np.mean(reference):.6f}, Std: {np.std(reference):.6f}")

if __name__ == "__main__":
    main()